package utils

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"igxe-change/config"
	"igxe-change/model"
	"io/ioutil"
	"net/http"
	"strings"
)

type OriginItem struct {
	Name       string
	ExtraPrice float64
	IsExtra    bool
}

func GetItemOriginInfo(name string) OriginItem {
	oi := OriginItem{Name: name, IsExtra: false}

	if strings.Index(name, "亲笔签名") == 0 {
		oi.IsExtra = true
		oi.Name = strings.Replace(name, "亲笔签名", "", -1)
		oi.ExtraPrice = 3.5
	}

	if strings.Index(name, "铭刻") == 0 {
		oi.IsExtra = true
		oi.Name = strings.Replace(name, "铭刻", "", -1)
		oi.ExtraPrice = 1.8
	}

	if strings.Index(name, "冥灵") == 0 {
		oi.IsExtra = true
		oi.Name = strings.Replace(name, "冥灵", "", -1)
		oi.ExtraPrice = 18
	}

	oi.Name = strings.TrimSpace(oi.Name)

	return oi
}

func LoginAndReturnToken(u *model.User) (string, error) {
	url := fmt.Sprintf("%s/rest/app/user/user_login", config.GetBaseUrl())

	lb := model.LoginBody{
		Username:   u.Username,
		Password:   u.Password,
		MCode:      config.GetMCode(),
		ClientType: 3,
	}

	body, _ := json.Marshal(lb)

	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(body))

	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/json")

	client := http.DefaultClient

	resp, err := client.Do(req)

	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", errors.New(resp.Status)
	}

	content, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return "", err
	}

	var result model.LoginResult

	json.Unmarshal(content, &result)

	if result.Code != SuccessCode {
		return "", errors.New(result.Message)
	}

	return result.Data.Token, nil
}
